package com.asset.dispoal.business.appoint.service.command;

import com.asset.dispoal.business.appoint.domain.db.entity.CaseAppoint;
import com.asset.dispoal.business.appoint.domain.db.mapper.AppointMapper;
import com.asset.dispoal.business.appoint.dto.AppointInsertRequest;
import com.asset.dispoal.business.appoint.service.converter.CaseAppointConverer;
import com.asset.dispoal.business.bsAgreement.domain.db.entity.BsCaseAppointMapper;
import com.asset.dispoal.business.bsCase.domain.db.entity.BsCase;
import com.asset.dispoal.business.bsCase.domain.db.entity.CaseStateRecord;
import com.asset.dispoal.business.bsCase.domain.db.mapper.BsCaseMapper;
import com.asset.dispoal.commom.menus.AgreementCaseSateMenu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class InsertAppointCommand implements BaseCommand<AppointInsertRequest, Result> {

    @Autowired
    BaseIdeable<String> snowFlake;


    @Autowired
    BsCaseMapper bsCaseMapper;

    @Autowired
    AppointMapper appointMapper;


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(AppointInsertRequest request) {
        String userId = GlobalHeaderThreadLocal.getOrException().getUserId();
        Date currentDate = DateTimeUtil.currentDate();
        //此处查询派案数
        //瑕疵
        List<String> caseIdList = bsCaseMapper.queryCaseIdCanAppointCase(request);
        if (CollectionUtil.isEmpty(caseIdList)) {
            return Result.faild("无可派送的案件数据");
        }
        CaseAppoint caseAppoint = CaseAppointConverer.INSTANCE.insertToDo(request);
        caseAppoint.setId(snowFlake.generateId());
        caseAppoint.setCreateUser(userId);
        caseAppoint.setCreateTime(currentDate);


        String oldState;
        if ("1".equals(request.getType())) {
            oldState = AgreementCaseSateMenu.WAIT_DELIVERY.getLabel();
        } else {

            Integer count = appointMapper.queryDropCountByAppointId(request.getWithdrawalAppointId());
            if (count <= caseIdList.size()) {
                appointMapper.removeDropId(request.getWithdrawalAppointId());
            }
            appointMapper.removeCaseIdList(caseIdList);
            if ("2".equals(request.getType())) {
                //退案委派 写入派案数据、以及更新派案相关数据、包含历史
                oldState = AgreementCaseSateMenu.WITHDRAWAL.getLabel();
            } else {
                //瑕疵池派案
                oldState = AgreementCaseSateMenu.FLAW.getLabel();
            }
        }

        List<BsCaseAppointMapper> mapperList = new ArrayList<>(caseIdList.size());
        for (String caseId : caseIdList) {
            BsCaseAppointMapper caseAppointMapper = new BsCaseAppointMapper();
            caseAppointMapper.setAppointId(caseAppoint.getId());
            caseAppointMapper.setId(snowFlake.generateId());
            caseAppointMapper.setDropStatus("0");
            caseAppointMapper.setOperateTime(currentDate);
            caseAppointMapper.setCaseId(caseId);
            caseAppointMapper.setOperateUser(GlobalHeaderThreadLocal.getOrException().getUserId());
            mapperList.add(caseAppointMapper);

            BsCase bsCase = new BsCase();
            bsCase.setId(caseId);
            bsCase.setCaseState(AgreementCaseSateMenu.DOWNLOAD_ORGER.getLabel());
            bsCase.setMergeImpLink(AgreementCaseSateMenu.DOWNLOAD_ORGER.getMerge());
            bsCase.setOperateTime(DateTimeUtil.currentDate());
            bsCase.setOperateUser(userId);
            bsCase.setPlaintiffId(request.getPlaintiffId());
            bsCase.setCourtId(request.getCourtId());
            bsCase.setLaywerId(request.getLawyerId1());
            bsCase.setLaywerId2(request.getLawyerId2());
            bsCase.setAppointBatchId(caseAppoint.getId());
            bsCase.setSueTime(request.getCalculationDate());
            bsCase.setSueFormulaId(request.getFormulaId());
            bsCaseMapper.downloadOrder(bsCase);

            CaseStateRecord caseStateRecord = new CaseStateRecord();
            caseStateRecord.setId(snowFlake.generateId());
            caseStateRecord.setOldState(oldState);
            caseStateRecord.setNewState(AgreementCaseSateMenu.DOWNLOAD_ORGER.getLabel());
            caseStateRecord.setCaseId(caseId);
            caseStateRecord.setCreateUser(userId);
            bsCaseMapper.insertStateRecord(caseStateRecord);
        }
        caseAppoint.setAppointCount(caseIdList.size());
        bsCaseMapper.saveBathAppointMapper(mapperList);
        appointMapper.insert(caseAppoint);
        appointMapper.insertRecord(caseAppoint);
        if (CollectionUtil.isNotEmpty(request.getEvidenceConfItemDetailIdList())) {
            appointMapper.insertConf(caseAppoint.getId(), request.getEvidenceConfItemDetailIdList());
        }
        return Result.ok();
    }
}
